package com.tajiang.business.common.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.gprinter.aidl.GpService;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.tajiang.business.R;
import com.tajiang.business.bluetooth.BTPrinterChooseActivity;
import com.tajiang.business.bluetooth.PortConfigurationActivity;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.businesscount.BusinessCountMenuFragment;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.fragment.BaseFragment;
import com.tajiang.business.common.utils.FragmentController;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.widget.BottomBarView;
import com.tajiang.business.model.Order;
import com.tajiang.business.order.fragment.OrderFragment;
import com.tajiang.business.search.fragment.SearchFragment;
import com.tajiang.business.setting.fragment.MySettingFragment;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/5/10.
 */
public class HomeActivity extends BaseActivity implements BottomBarView.OnBottomBarClickListener{

    private final static int DEFAULT_REFRESH_TIME         =  5 * 60 * 1000;        //定时器5分钟秒之后刷新订单页面

    public static final int PAGE_ORDER = 0;
    public static final int PAGE_SEARCH_ORDER = 1;
    public static final int PAGE_MESS = 2;
    public static final int PAGE_SETTING = 3;

    private long mExitTime;

    public static final String EXTRA_FROM_LOGIN = "extra_from_login";

    // 配置底部菜单栏内容
    private String[] labelArr = {"订单打印", "订单查询", "营业统计", "设置"};

    private int[] imgNormalResIdArr = {
            R.drawable.order_printing_unselected,
            R.drawable.order_tracking_unselected,
            R.drawable.business_statistics_unselected,
            R.drawable.set_up_unselected
    };

    private int[] imgPressedResIdArr = {
            R.drawable.order_printing,
            R.drawable.order_tracking,
            R.drawable.business_statistics,
            R.drawable.set_up
    };

    private List<Fragment> mFragmentList = new ArrayList<>();

    @BindView(R.id.nnvTabBarHome)
    BottomBarView nnvTabBarHome;

    private FragmentController controller;

    private MyCountDownTimer myCountDownTimer;

    int DEFAULT_PRINTER_NUM = 1;
    int mPrinterId = BTPrintUtils.PRINTER_ID;
    PortParameters mPortParams[] = new PortParameters[DEFAULT_PRINTER_NUM];

    private GpService mGpService;
    private PrinterServiceConnection conn = null;

    protected void onCreate(Bundle bundle){
        super.onCreate(bundle);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //返回到首页刷新金额
        ((BaseFragment) (mFragmentList.get(PAGE_MESS))).reFreshCurrentPageData();

        //定时自动刷新订单
        if (myCountDownTimer == null) {
            myCountDownTimer = new MyCountDownTimer(DEFAULT_REFRESH_TIME, DEFAULT_REFRESH_TIME);
        }
        myCountDownTimer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        LogUtils.e("HomeActivity ---> onPause");
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        LogUtils.e("HomeActivity ---> onDestroy");
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
        }

        if (conn != null) {
            unbindService(conn); // unBindService
        }
    }

    @Override
    protected void initTopBar() {
        disableNav();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        openBluetoothDevice();
    }

    /**
     * 连接蓝牙
     */
    private void connection() {

        conn = new PrinterServiceConnection();
        Log.i("【TEST】", "new PrinterServiceConnection()..connection");
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
        Log.i("【TEST】", "bindService,,,conn,,");
    }

    /**
     * 判断端口号是否已经开启
     */
    private void isBlueToothOpen() {

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            // 如果本地蓝牙没有开启，则开启
            if (mBluetoothAdapter.isEnabled() == false) {
                AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
                builder.setMessage("请开启蓝牙设备");
                builder.setTitle("提示");
                builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                builder.setCancelable(false);
                builder.create().show();
            }
        }
    }


    public void openBluetoothDevice() {
        // Get local Bluetooth adapter
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        // 如果adapter为null,蓝牙设备不支持
        if (bluetoothAdapter == null) {
            ToastUtils.showShort("硬件不支持蓝牙设备");
        } else {
            //打开蓝牙
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
                Intent enableIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent,
                        PortConfigurationActivity.REQUEST_ENABLE_BT);
            }else{
//                initPortParam();
            }
        }
    }

    @Override
    protected void initData() {

        nnvTabBarHome.initData(labelArr, imgNormalResIdArr, imgPressedResIdArr);
        nnvTabBarHome.setOnBottomBarClickListener(this);

        mFragmentList.add(new OrderFragment());
        mFragmentList.add(new SearchFragment());
//        mFragmentList.add(new MessFragment());
        mFragmentList.add(new BusinessCountMenuFragment());
        mFragmentList.add(new MySettingFragment());
//        mFragmentList.add(new SettingFragment());

        controller = new FragmentController(this, R.id.fl_home, mFragmentList);
    }

    @Override
    public void onBottomBarClick(int position) {

        switch (position) {
            case PAGE_ORDER:
                ((BaseFragment)(mFragmentList.get(position))).reFreshCurrentPageData();
                break;
            case PAGE_SEARCH_ORDER:
                ((BaseFragment) (mFragmentList.get(position))).reFreshCurrentPageData();
                break;
            case PAGE_MESS:
                ((BaseFragment) (mFragmentList.get(position))).reFreshCurrentPageData();
                break;
            case PAGE_SETTING:

                break;
            default:
                break;
        }

        Order.CURRENT_ORDER_STATE = position;
        controller.showFragment(position);
    }

    @Override
    public void onBackPressed() {

        long nowTime = System.currentTimeMillis();
        if (nowTime - mExitTime < 2000) {
            MobclickAgent.onKillProcess(this);
            TJApp.getInstance().exit();
        } else {
            mExitTime = nowTime;
            ToastUtils.showLong("再按一次退出");
        }
    }

    /**
     * 定时刷新OrderFragment页面的订单
     */
    private void refreshOrderFragment() {

        if (mFragmentList != null) {

            try{
                ((OrderFragment)(mFragmentList.get(PAGE_ORDER))).refreshOrderBySpecificTime();
            } catch (ClassCastException e) {
                LogUtils.e(e.toString());
            }
        }
    }

    class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            LogUtils.e("定时器" + DEFAULT_REFRESH_TIME + "ms 之后刷新订单页面");
            HomeActivity.this.refreshOrderFragment(); //定时刷新OrderFragment页面的订单
            this.start();
        }
        @Override
        public void onTick(long millisUntilFinished) {

        }
    }

    /**
     * ---------------初始化--------------
     * 从数据库获取上次存储组的已选设备的相关状态参数
     */
    private void initPortParam() {

        boolean state = getIntent().getBooleanExtra(BTPrinterChooseActivity.CONNECT_STATUS, false);
        PortParamDataBase database = new PortParamDataBase(this);
        mPortParams[mPrinterId] = new PortParameters();
        mPortParams[mPrinterId] = database.queryPortParamDataBase("" + mPrinterId);
        mPortParams[mPrinterId].setPortOpenState(state);
        String deviceName = mPortParams[mPrinterId].getUsbDeviceName();
        String BluetoothAddr = mPortParams[mPrinterId].getBluetoothAddr();

        registerPrinterStatueBroadcast(this);
        connection();
    }

    /**
     * 注册广播，接收打印机连接状态变更
     */
    private void registerPrinterStatueBroadcast(Context context) {

        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
        registerReceiver(PrinterStatusBroadcastReceiver, filter);

        Log.d("【TEST】", "注册广播,GpCom.ACTION_CONNECT_STATUS");
    }

    /**
     * 广播“打印机连接状态变更
     */
    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (GpCom.ACTION_CONNECT_STATUS.equals(intent.getAction())) {

                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                int id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0);
                Log.d("zd", "connect status " + type);

                if (type == GpDevice.STATE_CONNECTING) {

                    ToastUtils.showShort("蓝牙打印机连接成功");
                } else if (type == GpDevice.STATE_NONE) {

                } else if (type == GpDevice.STATE_VALID_PRINTER) {

                } else if (type == GpDevice.STATE_INVALID_PRINTER) {

                }
            }
        }
    };

    /// TODO: 17/4/21 【蓝牙打印】
    void connectOrDisConnectToDevice(int PrinterId) {

        if(mGpService == null){
            ToastUtils.showShort("mGpService == null");
            return;
        }

        mPrinterId = PrinterId;
        int rel = 0;
        Log.e("zd", String.valueOf(mPortParams[PrinterId].getPortOpenState()));
        if (mPortParams[PrinterId].getPortOpenState() == false) {   //如果未连接，则连接
            if (CheckPortParamters(mPortParams[PrinterId])) {
                //TODO....ADD...LOADING....
                try {
                    mGpService.closePort(mPrinterId);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                switch (mPortParams[PrinterId].getPortType()) {
                    case PortParameters.BLUETOOTH:
                        try {
                            rel = mGpService.openPort(PrinterId, mPortParams[PrinterId].getPortType(), mPortParams[PrinterId].getBluetoothAddr(), 0);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
                LogUtils.e("zd", "result :" + String.valueOf(r));
                if (r != GpCom.ERROR_CODE.SUCCESS) {

                    if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                        mPortParams[PrinterId].setPortOpenState(true);
                    } else {
                        ToastUtils.showShort(GpCom.getErrorText(r));
                    }
                }
            } else {
                ToastUtils.showShort(getString(R.string.port_parameters_wrong));
            }
        }
    }

    class PrinterServiceConnection implements ServiceConnection {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.i("ServiceConnection", "onServiceConnected() called");
            mGpService = GpService.Stub.asInterface(service);

            connectOrDisConnectToDevice(mPrinterId);
        }
    }

    Boolean CheckPortParamters(PortParameters param) {

        boolean rel = false;
        int type = param.getPortType();
        if (type == PortParameters.BLUETOOTH) {
            if (!param.getBluetoothAddr().equals("")) {
                rel = true;
            }
        }
        return rel;
    }

}